'use strict';

require('sugar');
var password = require('./password');
var certificate = require('./certificate');
var fs = require('fs');
var request = require('request');

var Provider = function (conf) {
  conf = conf || {};

  this.url = conf.url;
  this.contextPath = conf.contextPath || '';
  this.username = conf.username;
  this.password = conf.password;
  this.strictSSL = conf.strictSSL;
  this.logger = conf.logger || console; // default to console if logger not provided

  var self = this;
  var options = {};
  options.proxy = conf.proxy || false;
  if (conf.secureProtocol) {
    options.agentOptions = {
      secureProtocol: conf.secureProtocol
    };
  }
  options.strictSSL = this.strictSSL;
  if (this.strictSSL) {
    this.logger.info('Turning on strict SSL for', this.url);
    if (!conf.ca) {
      this.logger.error('No CA provided for', this.url);
      throw new Error('No CA provided for ' + this.url);
    }
    var calist = conf.ca.split(',');
    options.ca = [];
    calist.each(function (capath) {
      capath = capath.trim();
      self.logger.info('Installing certificate ' + capath);
      var buf = fs.readFileSync(capath);
      if (certificate.isPEM(buf)) {
        self.logger.info('Cert ' + capath + ' is in PEM format');
      } else {
        self.logger.info('Cert ' + capath + ' is in DER format, convert to PEM');
        buf = certificate.convertToPEM(buf);
      }
      options.ca.push(buf);
    });
  }
  this.request = request.defaults(options);
};

Provider.prototype.decryptPassword = function (keyfile) {
  this.password = password.decrypt2(this.password, keyfile);
};

Provider.prototype.getBasePath = function () {
  return this.url.add(this.contextPath);
};

Provider.prototype.getUrlPath = function (fragment) {
  return this.url.add(this.contextPath).add(fragment);
};

module.exports = exports = Provider;